package com.masterclient.app.businessmodule.usermodule.login.index;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.usermodule.login.beans.AuthBindData;
import com.masterclient.app.businessmodule.usermodule.login.beans.InviteInfoData;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginSuccessData;
import com.masterclient.app.businessmodule.usermodule.login.contract.QuickLoginContract;
import com.masterclient.app.businessmodule.usermodule.login.contract.QuickLoginPresenter;
import com.masterclient.app.businessmodule.usermodule.login.dialog.InviteDialog;
import com.masterclient.app.businessmodule.usermodule.login.invite.BindInviteActivity;
import com.masterclient.app.utils.CaptchaUtil;
import com.eoner.uikit.edits.CodeEditView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

@Route(path = AroutePath.LOGIN_CODE_LOGIN)
public class CodeLoginActivity extends FCBusinessActivity<QuickLoginPresenter> implements QuickLoginContract.View {

    @BindView(R.id.root)
    View root;
    @BindView(R.id.phont_txt)
    TextView phont_txt;
    @BindView(R.id.get_code_txt)
    TextView get_code_txt;
    @BindView(R.id.tv_code_verify)
    TextView tv_code_verify;

    @BindView(R.id.codeEditView)
    CodeEditView codeEditView;

    @Autowired(name = "phone")
    String phone;
    @Autowired(name = "from")
    String from;
    @Autowired(name = "intentSource")
    String intentSource;

    private CaptchaUtil captchaUtil;
    SPUtils spUtils;
    CountDownTimer timer;
    private String captcha;
    private String rewardId = "";;

    @Override
    protected int requireGetLayoutId() {
        return R.layout.code_login_activity;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setLineHidden(true);
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        init();
        initViews();
        addListener();
        mPresenter.mRxManager.mRxBus.OnEvent(mPresenter.mRxManager.mRxBus.register(Config.CODE_LOGIN_FINISH), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                finish();
            }
        });
        tv_code_verify.setClickable(false);
        tv_code_verify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("forgetPwdPage".equals(from)){
                    mPresenter.checkCaptcha(captcha,phone,"forget_password");
                }else {
                    mPresenter.quickLogin(phone,captcha,Config.uid,"");
                }
            }
        });
    }

    private void addListener() {
        codeEditView.setOnCodeFinishListener(new CodeEditView.OnCodeFinishListener() {
            @Override
            public void onFinish(String code) {
                captcha = code;
                tv_code_verify.setClickable(true);
                tv_code_verify.setBackgroundResource(R.drawable.login_able_click_bkg);
            }
        });

        codeEditView.setOnCodeUnFinishListener(new CodeEditView.OnCodeUnFinishListener() {
            @Override
            public void onUnFinish() {
                tv_code_verify.setClickable(false);
                tv_code_verify.setBackgroundResource(R.drawable.login_unable_click_bkg);
            }
        });

    }

    private void init() {

        captchaUtil = new CaptchaUtil(this,"forgetPwdPage".equals(from)?"忘记密码":"验证码登录");

        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                if ("forgetPwdPage".equals(from)){
                    mPresenter.getCaptcha(phone,"forget_password",ne);
                }else {
                    mPresenter.getCaptcha(phone,"slogin",ne);
                    get_code_txt.setClickable(false);
                }
            }

            @Override
            public void onFailed() {
                get_code_txt.setClickable(true);
            }
        });


        spUtils = SPUtils.getInstance();

        phont_txt.setClickable(false);
        timer = new CountDownTimer((60 * 1000), 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                String timeStr = "" + millisUntilFinished / 1000;
                String temp = timeStr + " 秒后重新发送";

                SpannableString spannableString = new SpannableString(temp);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#7399E5")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#141922")), timeStr.length(), temp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                get_code_txt.setText(spannableString);
            }

            @Override
            public void onFinish() {
                get_code_txt.setClickable(true);
                get_code_txt.setTextColor(Color.parseColor("#666666"));
                get_code_txt.setText("重新获取");
//                    String timeStr = "没收到验证码？";
//                    String temp = timeStr + " 重新发送";
//
//                    SpannableString spannableString = new SpannableString(temp);
//                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#141922")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#7399E5")), timeStr.length(), temp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    get_code_txt.setText(spannableString);
            }
        };
        timer.start();
    }

    Timer softInputTimer;
    private void initViews() {
        phont_txt.setText("已发送至 " + phone.substring(0,3) + " " + phone.substring(3,7) + " " + phone.substring(7,phone.length()));
        get_code_txt.setClickable(false);

        softInputTimer = new Timer();
        softInputTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                //TODO:fix (一加 报线程问题)
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        if (codeEditView != null) {
                            codeEditView.showSoftInput(null);
                        }
                    }
                });

            }

        },100);
    }

    @OnClick({R.id.get_code_txt})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_code_txt:
                codeEditView.clear();
                if(SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                    if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES){
                        if ("forgetPwdPage".equals(from)){
                            mPresenter.getCaptcha(phone,"forget_password","");
                        }else {
                            mPresenter.getCaptcha(phone, "slogin", "");
                        }
                    }else {
                        captchaUtil.start();
                    }
                }else {
                    if ("forgetPwdPage".equals(from)){
                        mPresenter.getCaptcha(phone,"forget_password","");
                    }else {
                        mPresenter.getCaptcha(phone,"slogin","");
                        get_code_txt.setClickable(false);
                    }
                }
                break;
                default:break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (codeEditView != null){
            codeEditView.hideSoftInput(null);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (resultCode){
            case 101:
                finish();
                return;
            case 107:
                finish();
                return;
        }
        if (requestCode == BindInviteActivity.REQUEST_CODE) {
            if (resultCode == BindInviteActivity.BIND_SUC_CODE) {
                setResult();
                getActivity().finish();
                if (!UtilActivity.isCurActivity("MainActivity")) {
                    startActivitryWithBundle(MainActivity.class, null);
                }
            }
        }
    }


    //TODO:通知登录成功
    /**
     * 登录成功刷新
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        baseHiddenCommitLoading();
        if(dialog!=null&&dialog.isShowing()) {
            dialog.dismiss();
        }
        if(timer != null){
            timer.cancel();
            timer = null;
        }
        if(softInputTimer != null){
            softInputTimer.cancel();
            softInputTimer = null;
        }
        if (mPresenter!=null && mPresenter.mRxManager!=null && mPresenter.mRxManager.mRxBus!=null) {
            mPresenter.mRxManager.mRxBus.unregister(Config.CODE_LOGIN_FINISH);
        }
    }

    @Override
    public void getCaptchaResult(String result) {
        phont_txt.setClickable(false);
        timer = new CountDownTimer((60 * 1000), 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                String timeStr = "" + millisUntilFinished / 1000;
                String temp = timeStr + " 秒后重新发送";

                SpannableString spannableString = new SpannableString(temp);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#7399E5")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#141922")), timeStr.length(), temp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                get_code_txt.setText(spannableString);
            }

            @Override
            public void onFinish() {
                get_code_txt.setClickable(true);
                String timeStr = "没收到验证码？";
                String temp = timeStr + " 重新发送";

                SpannableString spannableString = new SpannableString(temp);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#141922")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#7399E5")), timeStr.length(), temp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                get_code_txt.setText(spannableString);
            }
        };
        timer.start();
    }

    @Override
    public void showLogin(LoginSuccessData data) {
        login_success_next(data);
    }

    @Override
    public void showLoginFail(String msg, String failReason) {
        showToast(msg);
    }

    LoginSuccessData data;
    private void login_success_next(LoginSuccessData data) {
        if(!TextUtils.isEmpty(data.getCustomer_id())){
            SPUtils.getInstance().put(Config.CUSTOMERID_TEMP, data.getCustomer_id());
        }
        if(!TextUtils.isEmpty(data.getToken())){
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN_TEMP, data.getToken());
        }
        UserDataManager.getInstance().updateUserStatus(data.isIs_disable());
        this.data = data;
        if (data.getInviter_code_select_pop() != null && data.getInviter_code_select_pop().bindInviterCode != null){
            rewardId = data.getInviter_code_select_pop().bindInviterCode.rewardId;
        }
        spUtils.put(Config.QUICK_VERIFY_TIME,0l);
        if (data.isIs_disable()) {
            SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
            SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
            UtilActivity.finishStartNum(0, UtilActivity.getActivitySize());
            ARouter.getInstance().build(AroutePath.BAN_ACCOUNT_ACTIVITY)
                    .withString("content", data.getFreeze_reason()).navigation();
        }else if (data.isIs_show_code_select_pop() || data.isIs_show_user_info_pop()) {
            //绑定邀请人弹窗
//            show_pop_dialog(data);
            //TODO:fix
            //绑定邀请人弹窗
            Intent intent = new Intent(this, BindInviteActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("auth_type", "");
            bundle.putString("phone", phone);
            bundle.putString("union_id", "");
            bundle.putString("nick_name", "");
            bundle.putString("headimgurl", "");
            bundle.putSerializable("inviter_pop", data.getInviter_pop());
            bundle.putSerializable("lg_data",data);
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BindInviteActivity.REQUEST_CODE);


        }else {
            //已绑定
            login_success_convert();
        }
    }

    private void login_success_convert() {
        showToast("登录成功");
        SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
        SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
        UserDataManager.getInstance().updateUserStatus(data.isIs_disable());
        EventBusManager.post(EventBusManager.createLoginSuccessEvent());
        EventBusManager.post(EventBusManager.createHomeRefreshEvent());
        setResult();
        getActivity().finish();
        if (!UtilActivity.isCurActivity("MainActivity")) {
            startActivitry(MainActivity.class, null);
        }
    }

    private InviteDialog dialog;
    private void show_pop_dialog(LoginSuccessData data) {
        if (dialog == null) {
            dialog = new InviteDialog(getActivity(), new InviteDialog.OnChooseListener() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void getByInviteCode(String inviteCode) {
                    mPresenter.getInviteInfo(inviteCode);
                }

                @Override
                public void confirm(String inviteCode) {
                    //dialog.dismiss();
                    baseShowCommitLoading("登录中");
                    mPresenter.authBind("",phone, "",inviteCode,Config.uid,"","",
                            data.getNonce(),SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP),rewardId);

                }

                @Override
                public void skip_login() {
                    login_success_convert();
                }
            });
        }
        if (!dialog.isShowing()) {
            dialog.show();
            dialog.setData(data);
        }
    }

    private void setResult() {
        if(getIntent() != null && getIntent().getExtras() != null){
            Bundle bundle = getIntent().getExtras();
            String result = bundle.getString("result_code");
            if(!TextUtils.isEmpty(result)){
                setResult(Integer.valueOf(result));
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void authLoginData(LoginSuccessData data) {

    }

    @Override
    public void authLoginError(String msg, String failReason) {

    }

    @Override
    public void showError(String msg) {
        showToast(msg);
    }

    @Override
    public void checkSuccess() {
        Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.SET_NEW_PED_FRAGMENT)
                .withString("phone",phone)
                .withString("intentSource", intentSource)
                .withString("code",captcha).navigation();
        FragmentHostActivity.openFragment(getActivity(), fragment);

    }

    @Override
    public void checkError(String msg) {
        showToast(msg);
    }

    @Override
    public void showInviteInfo(InviteInfoData inviteInfoData) {
        rewardId = "";
        dialog.refreshInviteInfo(inviteInfoData,"");
    }

    @Override
    public void showInviteInfoFail(String msg) {
        dialog.refreshErrorInfo(msg);
    }

    @Override
    public void authBindSuccess(String code,AuthBindData data,String msg,String inviteCode) {
        UserDataManager.getInstance().updateInviteCode(inviteCode);
        if ("30000".equals(code)){
            rewardId = data.getInviteInfo().getReward_id();
            dialog.refreshInviteInfo(data.getInviteInfo(),data.getNotice());
        }else {
            if(dialog != null){
                dialog.dismiss();
            }
            if (data != null) {
                if(!TextUtils.isEmpty(data.getCustomer_id())){
                    SPUtils.getInstance().put(Config.CUSTOMERID, data.getCustomer_id());
                }else {
                    SPUtils.getInstance().put(Config.CUSTOMERID, SPUtils.getInstance().getString(Config.CUSTOMERID_TEMP));
                }
                if(!TextUtils.isEmpty(data.getToken())){
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, data.getToken());
                }else{
                    SPUtils.getInstance().put(Config.CUSTOMER_TOKEN, SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN_TEMP));
                }
            }
            EventBusManager.post(EventBusManager.createLoginSuccessEvent());
            EventBusManager.post(EventBusManager.createHomeRefreshEvent());
            setResult();
            getActivity().finish();
            if (!UtilActivity.isCurActivity("MainActivity")){
                startActivitry(MainActivity.class,null);
            }
        }
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    public void authBindFailded(String msg) {
        baseHiddenCommitLoading();
        showToast(msg);
    }



}
